package com.tfxy.hxl.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tfxy.hxl.R;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {

    // 硬编码白名单，避免配置读取问题
    private final List<String> whiteList = Arrays.asList(
        "/user/login",
        "/user/register", 
        "/actuator/**",
        "/swagger-ui/**",
        "/v3/api-docs/**",
        "/venue/list",
        "/venue/**",
        "/coach/list",
        "/coach/**"
    );

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();

        // 检查是否在白名单中
        if (isWhitePath(path)) {
            return chain.filter(exchange);
        }

        // 场馆和教练服务不需要认证
        if (path.startsWith("/venue/") || path.startsWith("/coach/")) {
            return chain.filter(exchange);
        }

        // 获取token
        String token = request.getHeaders().getFirst("token");
        if (!StringUtils.hasText(token)) {
            return unauthorized(exchange, "未登录");
        }

        // 验证token
        try {
            boolean isValid = com.tfxy.hxl.JwtUtils.checkToken(token);
            if (!isValid) {
                return unauthorized(exchange, "token无效");
            }
        } catch (Exception e) {
            return unauthorized(exchange, "token验证失败");
        }

        return chain.filter(exchange);
    }

    /**
     * 检查路径是否在白名单中
     */
    private boolean isWhitePath(String path) {
        for (String whitePath : whiteList) {
            if (antPathMatcher.match(whitePath, path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 返回未授权响应
     */
    private Mono<Void> unauthorized(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        R result = R.error().code(20001).message(message);
        ObjectMapper objectMapper = new ObjectMapper();
        String json;
        try {
            json = objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            json = "{\"code\":20001,\"message\":\"未授权\"}";
        }

        DataBuffer buffer = response.bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }
}
